﻿namespace Bowlus.Common
{
    using System.Collections.Generic;
    using System.Linq;

    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;

    public class BowlusContext : TableServiceContext
    {

        private const string TenantDeploymentTable = "TenantDeployment";

        private static readonly object LockObject = new object();

        private static volatile BowlusContext instance;

        private BowlusContext(CloudStorageAccount account)
            : base(account.TableEndpoint.AbsoluteUri, account.Credentials)
        {
            var ctc = new CloudTableClient(account.TableEndpoint.AbsoluteUri, account.Credentials);
            if (ctc.CreateTableIfNotExist(TenantDeploymentTable))
            {
                var td = new TenantDeployment { RowKey = "initalizer" };
                this.AddTenantDeployment(td);
                DeleteObject(td);
                SaveChanges();
            }
        }

        public static BowlusContext Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (LockObject)
                    {
                        if (instance == null)
                        {
                            return instance = new BowlusContext(Settings.DataConnectionString);
                        }
                    }
                }

                return instance;
            }
        }

        public IQueryable<TenantDeployment> TenantDeployment
        {
            get
            {
                return CreateQuery<TenantDeployment>(TenantDeploymentTable).Where(c => c.PartitionKey == "_bowlus");
            }
        }

        public void UpdateList(IEnumerable<TenantDeployment> td)
        {
            foreach (var deployment in td)
            {
                UpdateObject(deployment);
            }
            SaveChanges();
        }

        public void AddTenantDeployment(TenantDeployment td)
        {
            AddObject(TenantDeploymentTable, td);
            SaveChanges();
        }
    }
}
